package org.example.config;

import com.alibaba.fastjson.JSONObject;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class P6SPYConfig  implements MessageFormattingStrategy {
    
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    /**
     * 自定义sql日志打印
     *
     * @param connectionId 连接标识
     * @param now          执行时间
     * @param elapsed      执行秒数ms
     * @param category     statement
     * @param prepared     预编译sql语句
     * @param sql          真实的sql语句
     * @param url          数据库url连接
     * @return {@link String}
     */
    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
        Map<String, Object> message = new LinkedHashMap<>(4);
        if (StringUtils.isNoneBlank(prepared, sql) ) {
            message.put("SQL execute time:", this.format.format(new Date()));
            message.put("SQL explain time:", elapsed + "ms");
            String newPrepared = prepared.replace("   ", "").replace("\n", " ");
            message.put("SQL prepared:", newPrepared);
            String newSql = sql.replace("   ", "").replace("\n", " ");
            message.put("SQL real:", newSql);
        }
        return JSONObject.toJSONString(message.isEmpty() ? "" : message, true);
    }
}
